function trim(str) 
{
var res = jQuery.trim(str);
return res;
}

function time(){
return parseInt(new Date().getTime()/1000)
}

function my_photos_left_menu()
{
	 $('ul.acount li a').eq(2).click();
}

function my_videos_left_menu()
{
	 $('ul.acount li a').eq(3).click();
}

function my_messags_left_menu()
{
	 $('ul.acount li a').eq(1).click();
}

function my_adverts_left_menu()
{
	 $('ul.acount li a').eq(4).click();
}

function currentDate()
{
	 var month=new Array(12);
	 month[0]="01";
	 month[1]="02";
	 month[2]="03";
	 month[3]="04";
	 month[4]="05";
	 month[5]="06";
	 month[6]="07";
	 month[7]="08";
	 month[8]="09";
	 month[9]="10";
	 month[10]="11";
	 month[11]="12";	 
	
	 var d = new Date();
	 var year = d.getFullYear();
	 var m = month[d.getMonth()]; 
	 var day=d.getDate();
	 if (day<10)
	 {
		 day='0'+day; 
	 }
	 var time= d.toLocaleTimeString();
	 var result=year+'-'+m+'-'+day+' '+time;
	 
	 return result;
}

function formatDate(p_unixtime)
{
	 var month=new Array(12);
	 month[0]="января";
	 month[1]="февраля";
	 month[2]="марта";
	 month[3]="апреля";
	 month[4]="мая";
	 month[5]="июня";
	 month[6]="июля";
	 month[7]="августа";
	 month[8]="сентября";
	 month[9]="октября";
	 month[10]="ноября";
	 month[11]="декабря";	 
	
	 var d = new Date(p_unixtime*1000);
	 var year = d.getFullYear();
	 var m = month[d.getMonth()]; 
	 var day=d.getDate();
	 if (day<10)
	 {
		 day='0'+day; 
	 }
	 var time= d.toLocaleTimeString();
	 var result=year+'-'+m+'-'+day+' '+time;
	 var result=day+' '+m+' '+year+' г.';
	 
	 return result;
}

function formatDateTime(p_unixtime)
{
	 var month=new Array(12);
	 month[0]="января";
	 month[1]="февраля";
	 month[2]="марта";
	 month[3]="апреля";
	 month[4]="мая";
	 month[5]="июня";
	 month[6]="июля";
	 month[7]="августа";
	 month[8]="сентября";
	 month[9]="октября";
	 month[10]="ноября";
	 month[11]="декабря";	 
	
	 var d = new Date(p_unixtime*1000);
	 var year = d.getFullYear();
	 var m = month[d.getMonth()]; 
	 var day=d.getDate();
	 if (day<10)
	 {
		 day='0'+day; 
	 }
		
	 var time= d.toLocaleTimeString();
	 var result=year+'-'+m+'-'+day+' '+time;
	 var result=day+' '+m+' '+year+' г. в '+time;
	 
	 return result;
}
  
function birthDateToAge(birth) 
{
	 var date1 = birth;
	 var dd  = new Date();
	 dd.setTime(Date.parse(date1));

	 var now = new Date(),
     age = now.getFullYear() - dd.getFullYear();
	 return now.setFullYear(1972) < dd.setFullYear(1972) ? age - 1 : age;
}

function plural(n)  {var m=n%10, l=n%100; return n + ' ' + (((m==1)&&(l!=11))?'год':(((m==2)&&(l!=12)||(m==3)&&(l!=13)||(m==4)&&(l!=14))?'года':'лет'))}


function currentYear()
{
	 var month=new Array(12);
	 month[0]="01";
	 month[1]="02";
	 month[2]="03";
	 month[3]="04";
	 month[4]="05";
	 month[5]="06";
	 month[6]="07";
	 month[7]="08";
	 month[8]="09";
	 month[9]="10";
	 month[10]="11";
	 month[11]="12";	 
	
	 var d = new Date();
	 var year = d.getFullYear();
	 var m = month[d.getMonth()]; 
	 var day=d.getDate();
	 if (day<10)
	 {
		 day='0'+day; 
	 }
	 var time= d.toLocaleTimeString();
	 var result=year+'-'+m+'-'+day;
	 
	 return result;
}

function isYoutubeLink(link) { 
   return /^(https?:\/\/)?([^\/]*\.)?youtube\.com\/watch\?([^]*&)?v=\w+(&[^]*)?/i.test(link); 
} 


String.prototype.replaceAll=function(find, replace_to)
{
    return this.replace(new RegExp(find, "g"), replace_to);
};


function AJAX (p_script_name, p_action, p_data, p_method, p_ajax_type, p_callback)
{
   $.ajax
	(
		{
			url: "ajax/"+p_script_name,
			type: p_method,
			data: 
			{
				 'data': p_data,					
				 'action': p_action 								
			},
			dataType: 'json',
			async: p_ajax_type,				
			success: p_callback
		}	
	);	
}

function countUnreadMessages()
{
	 var data={};
	 
	 var f=function(response)
	 {
		 if (response.count>0)
		 {
			 $('#column-left ul li a').eq(1).css('font-weight','bold');
			 $('#column-left ul li a').eq(1).html('Мои сообщения'+' ('+response.count+')');
			 if ($('#mail-container').size()!=0 && $('#mail-history').size()==0)
			 {
				 $('#column-left ul li a').eq(1).click();
			 }
		 }
		 else
		 {
			 $('#column-left ul li a').eq(1).css('font-weight','normal');
			 $('#column-left ul li a').eq(1).html('Мои сообщения');
		 }
	 }
	 var res = AJAX ("messages.php", "count_unread_messages", JSON.stringify(data), "POST", true, f);
}

function update_online_status() {

	 var f=function(response)
	 {
		
	 }
	 var res = AJAX ("visitors_online.php", "update_visited_time", null, "POST", true, f);

}

function login ()
{
	 if (validate_login_form()) return;
	 
	 var loginData = {};
	 loginData.email=$('#login_form input[name="email"]').val();
	 loginData.password=$('#login_form input[name="password"]').val();
	
	 var f=function(response)
	 {
		 if (response.status=="ok")
		 {
			 if (true !== response.http_referer.indexOf('external')) 
			 {
				 location.href=response.http_referer;
			 }
			 else
			 {
				 location.href='my_account.php';
			 }
   			 
		 }
		 else
		 {
			 if (response.status=="not auth")
			 {
				$('#login_form div#error').text("Неверный email или пароль!"); 
			 }
			 else
			 {
				 $('#login_form div#error').text(response.status);  
			 }
			 
		 }
	 }
	 var res = AJAX ("login.php", "login", JSON.stringify(loginData), "POST", true, f);	
	 
}

function validate_login_form()
{
	 var stop=false;
	
	 var email=$('#login_form input[name="email"]').val();	
	 var password=$('#login_form input[name="password"]').val();
	 
	 if (!$.trim(email))
		{
			$('#login_form div#error').text("E-Mail и пароль не могут быть пустыми");
			stop=true;
			return stop;
		}
	else 
		$('#login_form div#error').text("");
	if (!$.trim(password))
		{
			$('#login_form div#error').text("E-Mail и пароль не могут быть пустыми");
			stop=true;
		}
	else 
		$('#login_form div#error').text("");	
		
	if (!IsValidateEmail($.trim(email)))
		{
			$('#login_form div#error').text("E-Mail имеет некорректный формат!");
			stop=true;
		}	
		
	return stop;
}

function registration ()
{
     if (validate_reg_form()) return;
	 
	 var regData = {};
	 regData.email=$('#reg input[name="email"]').val();
	 regData.password=$('#reg input[name="password"]').val();
	 regData.first_name=$('#reg input[name="first_name"]').val();
	 regData.last_name=$('#reg input[name="last_name"]').val();	 
	 var f=function(response)
	 {
		 if (response.request=="ok")
		 location.href='my_account.php';
	 }
	 var res = AJAX ("registration.php", "registration", JSON.stringify(regData), "POST", true, f);	 
};

function IsValidateEmail(email) {
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/;
      return reg.test(email);
}

function validate_reg_form()
{
	var stop=false;
	
	var email=$('#reg_form input[name="email"]').val();
	var f_name=$('#reg_form input[name="first_name"]').val();
	var l_name=$('input[name="last_name"]').val();
	var password=$('#reg_form input[name="password"]').val();
	
	if (!$.trim(f_name))
		{
			$('#reg_form span.error').eq(2).text("Имя не может быть пустым");
			stop=true;
		}
	else 
		$('#reg_form span.error').eq(2).text("");
	if (!$.trim(l_name))
		{
			$('#reg_form span.error').eq(3).text("Фамилия не может быть пустой");
			stop=true;
		}
	else 
		$('#reg_form span.error').eq(3).text("");
	if (!$.trim(email))
		{
			$('#reg_form span.error').eq(0).text("E-Mail не может быть пустым");
			stop=true;
		}
	else 
		$('#reg_form span.error').eq(0).text("");
	if (!$.trim(password))
		{
			$('#reg_form span.error').eq(1).text("Пароль не может быть пустым");
			stop=true;
		}
	else 
		$('#reg_form span.error').eq(1).text("");	
		
	if (!IsValidateEmail($.trim(email)))
		{
			$('#reg_form span.error').eq(0).text("E-Mail имеет некорректный формат!");
			stop=true;
		}	
		
	return stop;
};

function photo_album(id, action)
{
	 var data={};
	 
	 data.id=id;
	 	 
	 if (action=="create_new_photoalbum")
	 {
		 var f=function(response)
		 {
			 get_all_albums ('photo');
			 $('#popup_photoalbum_edit').fadeOut(300);
		 }
		 data.photoalbum_name=$('#popup_photoalbum_edit input').val();
		 var res = AJAX ("personal_data.php", "create_new_photoalbum", JSON.stringify(data), "POST", true, f);
	 }
	 else if (action=="delete_photo_album")
	 {
		 var f=function(response)
		 {
			 get_all_albums ('photo');
			 $('#popup_confirm').fadeOut(300);
		 }
		 var res = AJAX ("personal_data.php", "delete_photo_album", JSON.stringify(data), "POST", true, f);
	 }
	 else if (action=="edit_photoalbum_name")
	 {
		 var f=function(response)
		 {
			 get_all_albums ('photo');
			 $('#popup_photoalbum_edit').fadeOut(300);
		 }
		 data.photoalbum_name=$('#popup_photoalbum_edit input').val();
		 var res = AJAX ("personal_data.php", "edit_photoalbum_name", JSON.stringify(data), "POST", true, f);
	 }
     
      else if (action=="new_photo_name")
	 {
		 var f=function(response)
		 {
			 var new_name=$('#popup_photoalbum_edit input.field').val();
             if (new_name.length>20)
             {
                 new_name=new_name.substr(0,18)+'...';
             }
             $('a[href="'+id+'"]').parent().find('div.photo_description').html(new_name);
             $('#hide-layout').fadeOut(300);
             $('#popup_photoalbum_edit').fadeOut(300);
		 }
         data.title=$('#popup_photoalbum_edit input.field').val();
         data.id=id.substr(id.lastIndexOf("/")+1);
         var res = AJAX ("personal_data.php", "new_photo_name", JSON.stringify(data), "POST", true, f);
	 }
      else if (action=="delete_current_photo")
	 {
		 var f=function(response)
		 {
			 $('a[href="'+id+'"]').parent().remove();
             $('#hide-layout').fadeOut(300);
             $('#popup_confirm').fadeOut(300);
		 }
         data.key=id.substr(id.lastIndexOf("/")+1);
         var res = AJAX ("personal_data.php", "delete_current_photo", JSON.stringify(data), "POST", true, f);
	 }
	 
}

function video_album(id, action)
{
	 var data={}, markup, short_name, link_key;
	 
	 data.id=id;
	 	 
	 if (action=="create_new_videoalbum")
	 {
		 var f=function(response)
		 {
			 get_all_albums ('video');
			 $('#popup_videoalbum_edit').fadeOut(300);
		 }
		 data.photoalbum_name=$('#popup_videoalbum_edit input').val();
		 var res = AJAX ("personal_data.php", "create_new_videoalbum", JSON.stringify(data), "POST", true, f);
	 }
	 else if (action=="delete_video_album")
	 {
		 var f=function(response)
		 {
			 get_all_albums ('video');
			 $('#popup_confirm').fadeOut(300);
		 }
		 var res = AJAX ("personal_data.php", "delete_video_album", JSON.stringify(data), "POST", true, f);
	 }
	 else if (action=="edit_videoalbum_name")
	 {
		 var f=function(response)
		 {
			 get_all_albums ('video');
			 $('#popup_videoalbum_edit').fadeOut(300);
		 }
		 data.photoalbum_name=$('#popup_videoalbum_edit input').val();
		 var res = AJAX ("personal_data.php", "edit_videoalbum_name", JSON.stringify(data), "POST", true, f);
	 }    
     else if (action=="upload_video")
     {
         var url_yourtube=$('#popup_videoalbum_edit input.field').val();
         
         if (!isYoutubeLink(url_yourtube))
         {
             alert ('Ссылка имеет некорректный формат. Убедитесь, что это ссылка с сервиса YouTube');
             return;
         }
         
          var f=function(response)
		 {
			  $('#ajax_loader_album_present').remove();
              if (response.status=='not uploaded')
              {
                 alert('Видео не было загружено');
                 return;
              }
              else
              {
                 $('#popup_videoalbum_edit').fadeOut(300);
                 $('#hide-layout').fadeOut(300);
                 
                 title= response.title;
                 short_name=title;
                 link_key=response.link_key;
                 
                 if (short_name.length>20)
                 {
                     short_name=short_name.substr(0,18)+'...';
                 }
                 markup = markup_video_block.replaceAll('##link_key##',link_key);
                 markup = markup.replace('##video_title_short##',short_name);
                 markup = markup.replace('##video_title##',title);
                 
                 if ($('#videoalbum_gallery span.no_photos').size()>0)
                 {
                      $('#videoalbum_wrap').html(markup_video_wrap_content);
                      $('#videoalbum_gallery_list').html(markup);
                 }
                 else
                 {
                     $('#videoalbum_gallery_list').append(markup);
                 } 
              }			 
		 }
		 data.url_yourtube=url_yourtube;
         $('#videoalbum_wrap').append(ajax_album_loader_present);
		 var res = AJAX ("personal_data.php", "upload_video", JSON.stringify(data), "POST", true, f);
     }
     else if (action=="new_video_info")
	 {
		 var f=function(response)
		 {
			 var new_name=$('#popup_videoalbum_edit input.field').val();
             if (new_name.length>20)
             {
                 new_name=new_name.substr(0,18)+'...';
             }
             $('img[video="'+id+'"]').parent().find('div.video_description').html(new_name);
             $('#hide-layout').fadeOut(300);
             $('#popup_videoalbum_edit').fadeOut(300);
		 }
         data.title=$('#popup_videoalbum_edit input.field').val();
         data.key=id;
         var res = AJAX ("personal_data.php", "new_video_info", JSON.stringify(data), "POST", true, f);
	 }
      else if (action=="delete_current_video")
	 {
		 var f=function(response)
		 {
			 $('img[video="'+id+'"]').parent().remove();
             $('#hide-layout').fadeOut(300);
             $('#popup_confirm').fadeOut(300);
		 }
         data.key=id;
         var res = AJAX ("personal_data.php", "delete_current_video", JSON.stringify(data), "POST", true, f);
	 }
}

function get_all_albums (p_album_type, p_elem)
{
     var data={};
     var header_title, header_block, markup;
     data.album_type=p_album_type;
	 
	 $('ul.acount li a').removeClass('active_item');
	 $(p_elem).addClass('active_item');
	 
	 if (p_album_type=='photo')
     {
         header_title='Мои фото';
     }
     else
     {
         header_title='Мои видео';
     }
     
     header_block=markup_header.replace('##title##',header_title);
     $('#content').html(header_block);
     
     var f=function(response)
	 {
		 $('#ajax_loader_album').remove();
         if (response.status=='no albums')
		 {
			 markup=markup_album_wrap_no.replaceAll('##album_type##',p_album_type);            
             $('#content').append(markup);
		 }
		 else
		 {
			var id, title;
			
			markup=markup_album_wrap.replaceAll('##album_type##',p_album_type);  
            $('#content').append(markup);
			
			for(resp in response) 
			{					 
				 title= response[resp].title;
				 id = response[resp].id;
				 markup = markup_album.replace('##album_id##',id);
				 markup= markup.replace('##name##',title);
                 markup= markup.replaceAll('##album_type##',p_album_type);
				 if (p_album_type=='photo')
                 {
                     $('#photoalbum_list').append(markup);
                 }
                 else
                 {
                     $('#videoalbum_list').append(markup);
                 }
                 				 
			}
		 }
		 
		 $('#hide-layout').fadeOut(300);
		 
	 }
     $('#content').append(ajax_album_loader);
	 var res = AJAX ("personal_data.php", "get_all_albums", JSON.stringify(data), "POST", true, f);	 
}

function get_albums_of_user (p_album_type, p_user_id)
{
   	 var data={};
     var header_title, header_block, markup;
     data.album_type=p_album_type;
	 data.user_id=p_user_id;
	 
	 if (p_album_type=='photo')
     {
         header_title='Фотоальбомы пользователя';
     }
     else
     {
         header_title='Видеоальбомы пользователя';
     }
     
     header_block=markup_header.replace('##title##',header_title);
     $('#content').html(header_block);
     
     var f=function(response)
	 {
		 $('#ajax_loader_album').remove();
         if (response.status=='no albums')
		 {
			 markup=markup_album_wrap_no.replaceAll('##album_type##',p_album_type);            
             $('#content').append(markup);			
		 }
		 else
		 {
			var id, title;
			
			markup=markup_album_wrap.replaceAll('##album_type##',p_album_type);  
            $('#content').append(markup);
			
			for(resp in response) 
			{					 
				 title= response[resp].title;
				 id = response[resp].id;
				 markup = markup_album.replace('##album_id##',id);
				 markup= markup.replace('##name##',title);
                 markup= markup.replaceAll('##album_type##',p_album_type);
				 if (p_album_type=='photo')
                 {
                     $('#photoalbum_list').append(markup);
                 }
                 else
                 {
                     $('#videoalbum_list').append(markup);
                 }                 				 
			}			
		 }		 
		 $('input[name$="album"]').remove();
		 $('div[class*="_control"]').remove();
		 markup = markup_back_user_profile.replaceAll('##user_id##',p_user_id);     
		 $('div[id*="album_wrap"]').append(markup);
	 }
     $('#content').append(ajax_album_loader);
	 var res = AJAX ("personal_data.php", "get_albums_of_user", JSON.stringify(data), "POST", true, f);	 
}

function back_user_profile(p_user_id)
{
	 location.href="user_profile.php?id="+p_user_id;
}

function get_photos(photoalbum_id, p_user_id)
{
     var data={}, markup, short_name, photos;
     data.photoalbum_id=photoalbum_id;
	 data.user_id=p_user_id;
	 
	 if ($('.content-filter').size()!=0)
	 {
		 var header_block=markup_header.replace('##title##','Фотографии пользователя');
		 $('#content').html(header_block);
	 }
	 else
	 {
		 $('.breadcrumb span').html('Фотографии пользователя');
	 }
     
     var f=function(response)
     {
         $('#ajax_loader_album').remove();
         if (response.status=='no photos')
		 {
			 
             $('#photoalbum_wrap').remove();
             $('#content').append(markup_no_photos_in_photoalbum);
             $('#photoalbum_wrap').append(markup_photos_form);
			 if (response.source!="my")
			{
				 markup = markup_back_user_profile_photoalbum.replaceAll('##user_id##',p_user_id);     
				 $('div[id*="gallery"]').append(markup);			 
			}			 
		 }
         else
         {             
             photos=response.photos;
			 $('#content').append(markup_photo_block_wrap);
             for(resp in photos)
             {
                 title= photos[resp].title;
                 short_name=title;
                 link = photos[resp].link_name;                  
                 if (short_name.length>20)
                 {
                     short_name=short_name.substr(0,18)+'...';
                 }
                 markup = markup_photo_block.replace('##photo_title##',title);
                 markup = markup.replace('##photo_title_short##',short_name);
                 markup = markup.replaceAll('##photo_link##',link);
                 $('#photoalbum_gallery_list').append(markup);           
             }
             $('#photoalbum_gallery').append(button_load_photo);
             $('#photoalbum_gallery').append(markup_photos_form);
             $("a[class^='gallery']").prettyPhoto();
         }
		 if (response.source!="my")
		 {
			 $('div[class*="_control"], input[name="upload_photo_btn"]').remove();
			 markup = markup_back_user_profile_album.replaceAll('##user_id##',p_user_id);  
			 markup = markup.replaceAll('##album_type##','photo'); 
			 $('div[id*="gallery_list"]').append(markup);			 
		 }
		 
     }
     
     $('#photoalbum_wrap').remove();
     $('#content').append(ajax_album_loader);
     var res = AJAX ("personal_data.php", "get_photos_from_album", JSON.stringify(data), "POST", true, f);	
}

function get_videos(videoalbum_id, p_user_id)
{
      var data={}, markup, short_name, link_key, videos;
      data.videoalbum_id=videoalbum_id;
      data.user_id=p_user_id;
	  
	 if ($('.content-filter').size()!=0)
	 {
		 var header_block=markup_header.replace('##title##','Видео пользователя');
		 $('#content').html(header_block);
	 }
	 else
	 {
		 $('.breadcrumb span').html('Видео пользователя');
	 }
	  
      var f=function(response)
     {
         $('#ajax_loader_album').remove();
         if (response.status=='no videos')
		 {			 
             $('#videoalbum_wrap').remove();
             $('#content').append(markup_no_videos_in_videoalbum);            
		 }
         else
         {             
            videos=response.videos;
			$('#content').append(markup_video_block_wrap);
             for(resp in videos)
             {
                 title= videos[resp].title;
                 short_name=title;
                 link_key = videos[resp].link_name;                  
                 if (short_name.length>20)
                 {
                     short_name=short_name.substr(0,18)+'...';
                 }
                 markup = markup_video_block.replaceAll('##link_key##',link_key);
                 markup = markup.replace('##video_title_short##',short_name);
                 markup = markup.replace('##video_title##',title);
                 $('#videoalbum_gallery_list').append(markup);           
             }
              $('#videoalbum_gallery').append(button_load_video);            
         }
		  if (response.source!="my")
		 {
			 $('div[class*="_control"], input[name="upload_video_btn"]').remove();
			 markup = markup_back_user_profile_album.replaceAll('##user_id##',p_user_id);  
			 markup = markup.replaceAll('##album_type##','video'); 
			 $('div[id*="gallery_list"]').append(markup);			 
		 }
     }
     
     $('#videoalbum_wrap').remove();
     $('#content').append(ajax_album_loader);
     var res = AJAX ("personal_data.php", "get_videos_from_album", JSON.stringify(data), "POST", true, f);	
}

function get_messages(p_elem)
{
	 $('ul.acount li a').removeClass('active_item');
	 $(p_elem).addClass('active_item');
	 
	 header_block=markup_header.replace('##title##','Мои сообщения');
     $('#content').html(header_block);
	 $('#content').append(mail_container);
	 
	 var data={};
	 var markup;
	 var f=function(response)
     {
		 $('#ajax_loader_album').remove();
		 for(resp in response)
		 {
			 message_id=response[resp].id;
			 sender_id=response[resp].sender_id;
			 receiver_id=response[resp].receiver_id;
			 date=response[resp].date;
			 message_body=response[resp].body;
			 message_status=response[resp].status;
			 sender_ava=response[resp].sender_ava;
			 receiver_ava=response[resp].receiver_ava;
			 my_id=response[resp].my_id;
			 
			 markup=markup_message.replaceAll('##message##',message_body);	
			 markup=markup.replaceAll('##date##',date);	
			 markup=markup.replaceAll('##message_id##',message_id);
			 markup=markup.replaceAll('##sender_id##',sender_id);
			 markup=markup.replaceAll('##receiver_id##',receiver_id);
			 markup=markup.replaceAll('##my_id##',my_id);
			 if (sender_ava !=null)
			 {
				 markup=markup.replaceAll('##sender_ava##','user_photos/mini/'+sender_ava);
			 }
			 else 
			 {
				 markup=markup.replaceAll('##sender_ava##','images/no_avatar50.png');
			 }
			 
			 if (receiver_ava !=null)
			 {
				 markup=markup.replaceAll('##receiver_ava##','user_photos/mini/'+receiver_ava);
			 }
			 else 
			 {
				 markup=markup.replaceAll('##receiver_ava##','images/no_avatar50.png');
			 }
			 
			 $('#mail-msg-list').append(markup);
			 if (receiver_id==my_id && message_status=='unread')
			 {
				 $('#mail-msg-list div.mail-msg').last().attr('class','mail-msg-unread');
			 }
			 
		 }
	 }
	 $('#content').append(ajax_album_loader);
	 var res = AJAX ("messages.php", "get_messages", JSON.stringify(data), "POST", true, f);	
	 
}

function advert(id, action)
{
	 var AdvertData={};
	 AdvertData.id=id;
	 AdvertData.action=action;
	 AdvertData.rubric=$('select[name="rubric_select"]').val();
	 AdvertData.category=$('select[name="kateg_select"]').val();
	 AdvertData.ekip_type=$('select[name="ekip_type"]').val();
	 AdvertData.text=$('textarea[name="advert_message"]').val();
	 AdvertData.phone=$('input[name="phone"]').val();
	 AdvertData.skype=$('input[name="scype"]').val();
	 AdvertData.email=$('input[name="email"]').val();
	 
	 if (action=="new_advert")
	 {
		  var f=function(response)
		{
			 $('#popup_edit_advert').fadeOut(300);
			 $('#hide-layout').fadeOut(300);
			 $('a.active_item').click();
		}
		  var res = AJAX ("advert.php", "new_advert", JSON.stringify(AdvertData), "POST", true, f);
	 }
	 
	  if (action=="delete_advert")
	 {
		  var f=function(response)
		{
			 $('#popup_confirm').fadeOut(300);
			 $('#hide-layout').fadeOut(300);
			 $('input[name="id"][value="'+id+'"]').parent().remove();
		}
		  var res = AJAX ("advert.php", "delete_advert", JSON.stringify(AdvertData), "POST", true, f);
	 }
	 
	  if (action=="edit_advert")
	 {
		  var f=function(response)
		{
			 $('#popup_edit_advert').fadeOut(300);
			 $('#hide-layout').fadeOut(300);
			 $('input[name="id"][value="'+id+'"]').parent().find('table td').eq(1).text($('#popup_edit_advert select :selected').eq(0).text());
			 $('input[name="id"][value="'+id+'"]').parent().find('table td').eq(3).text($('#popup_edit_advert select :selected').eq(1).text());
			 $('input[name="id"][value="'+id+'"]').parent().find('.article_content').text($('#popup_edit_advert textarea').val());
			 
		}
		  var res = AJAX ("advert.php", "edit_advert", JSON.stringify(AdvertData), "POST", true, f);
	 }
}


function popup_close()
{ 
	$('#hide-layout, #popup_confirm, #popup_contacts, #popup_photoalbum_edit, #popup_videoalbum_edit, #popup_edit_advert, #popup_message').fadeOut(300);
		
}

function ajax_send_crop_data()
{
	
	var form_data = $("#form_crop").serialize();	
		
	$.ajax({
		url: 'crop.php',
		type: 'POST', 
		data: form_data
	});	
}


function save_my_account_data()
{
	 var UserData={};
	 UserData.firstName=$('input[name="user_name"]').val();
	 UserData.lastName=$('input[name="user_surname"]').val();
	 UserData.dayOfBirth=$('select[name="day_of_birth"]').val();
	 UserData.monthOfBirth=$('select[name="month_of_birth"]').val();
	 UserData.yearOfBirth=$('select[name="year_of_birth"]').val();
	 UserData.contry=$('select[name="contry"]').val();
	 UserData.region=$('select[name="region"]').val();
	 UserData.city=$('select[name="city"]').val();
	 UserData.height=$('select[name="height"]').val();
	 UserData.weigth=$('select[name="weigth"]').val();
	 UserData.squat=$('input[name="squat"]').val();
	 UserData.press=$('input[name="press"]').val();
	 UserData.deadlift=$('input[name="deadlift"]').val();
	 UserData.level=$('select[name="level"]').val();
	 
	 var federationObject = {};
	 var federation_name; 
	 var federation_status;
	 
	 $('#popup_edit table').eq(2).find('input[type="checkbox"]').each
	(
		function()
		{
			federation_name=$(this).attr("name");
			if ($(this).parent().hasClass("checked"))
			{
				 federation_status=true;
			}
			else
			{
				 federation_status=false;
			}
			federationObject[federation_name] = federation_status;			
		}
	);
	 
	 UserData.federation=federationObject;
	 
	 var f=function(response)
	 {
		 if (response.status=="ok")
		 {
			 location.reload();
		 }
		 else
		 {
			 alert(response.status);
		 }
	 }
	 var res = AJAX ("personal_data.php", "save_personal_data", JSON.stringify(UserData), "POST", true, f);	 
	 
}

function ajax_get_mail_conversation(receiver, sender, p_object)
{
	var data={}, markup; 
	var prev=null;
	data.receiver=receiver;
	data.sender=sender;
	
	var f=function(response)
	 {
		 if (response.status=="no messages")
		 {
			 return;
		 }
		 else
		 {
			 $(p_object).after(mail_write_wrapper);
			 		 
			 for(resp in response)
			 {
				 sender_id=response[resp].sender_id; 
				 receiver_id=response[resp].sender_id;
				 date=response[resp].date;
				 body=response[resp].body;
				 my_id=response[resp].my_id;
				 receiver_ava=response[resp].receiver_ava;
				 sender_ava=response[resp].sender_ava;
				 
				 if (sender_id==my_id)
				 {
					 markup=mail_msg_me.replaceAll('##date##', date);
					 markup=markup.replaceAll('##message##', body);
					 if (sender_ava!=null)
					 {
						 markup=markup.replaceAll('##ava_me##', 'user_photos/mini/'+sender_ava);
					 }
					 else
					 {
						 markup=markup.replaceAll('##ava_me##', 'images/no_avatar50.png');
					 }
						 
					 if (prev==null||prev!=sender_id)
					 {
						 $('#mail-history').append(markup); 
						 prev=sender_id;
					 }
					 else
					 {
						 $('.mail-msg-me').last().find('div:nth-child(1)').find('div:nth-child(1)').append(mail_msg_separate);
						 markup=short_message.replaceAll('##date##', date);
						 markup=markup.replaceAll('##message##', body);
						 $('.mail-msg-me').last().find('div:nth-child(1)').find('div:nth-child(1)').append(markup);
						 prev=sender_id;
					 }
					 
				 }
				 else
				 {
					 markup=mail_msg_person.replaceAll('##date##', date);
					 markup=markup.replaceAll('##message##', body);
					 if (sender_ava!=null)
					 {
						 markup=markup.replaceAll('##ava_person##', 'user_photos/mini/'+sender_ava);
					 }
					 else
					 {
						 markup=markup.replaceAll('##ava_person##', 'images/no_avatar50.png');
					 }
						 
					 if (prev==null||prev!=sender_id)
					 {
						 $('#mail-history').append(markup); 
						 prev=sender_id;
					 }
					 else
					 {
						 $('.mail-msg-person').last().find('div:nth-child(1)').find('div:nth-child(1)').append(mail_msg_separate);
						 markup=short_message.replaceAll('##date##', date);
						 markup=markup.replaceAll('##message##', body);
						 $('.mail-msg-person').last().find('div:nth-child(1)').find('div:nth-child(1)').append(markup);
						 prev=sender_id;
					 }
				 }
			 }
			 
			 $('#mail-write-wrapper').show();
			 
			 if ($(p_object).attr('class')=='mail-msg-unread')
			 {
				$(p_object).attr('class','mail-msg');
				var d=function(response)
				{
					 countUnreadMessages();
				}
				 var res = AJAX ("messages.php", "update_messages_status", JSON.stringify(data), "POST", true, d);
				 
			 }
		 }	 
	 }
	 
	 var res = AJAX ("messages.php", "get_messages_conversation", JSON.stringify(data), "POST", true, f);	 	
}

function send_message()
{
	 $('#mail-write-wrapper').append(ajax_album_loader_present);
	 var my_id=$('#mail-write-wrapper').prev().find('input[name="my_id"]').val();
	 var type=$('#mail-write-wrapper').prev().find("input[value='"+my_id+"']").attr('name');
	 var sender_ava=$('#mail-write-wrapper').prev().find('input[name="sender_ava"]').val();
	 
	 if (type=='receiver_id')
	 {
		 sender_ava=$('#mail-write-wrapper').prev().find('input[name="receiver_ava"]').val();
	 }
	 
	 var receiver_id=$('#mail-write-wrapper').prev().find('input[name="receiver_id"]').val();
	 if (my_id==receiver_id)
	 {
		 receiver_id=$('#mail-write-wrapper').prev().find('input[name="sender_id"]').val();
	 }
	 
	 var message=$('#mail-write-wrapper').find('textarea').val();	 
	 var data={}, markup;
	 var date=currentDate();
	 data.receiver_id=receiver_id;
	 data.message=message;
	 
	 	 
	 var f=function(response)
	 {
		 $('#ajax_loader_album_present').remove();
		 
		 if (response.status!='message sent')
		 {
			 alert("Сообщение не было отправлено, возникли технические проблемы. Попробуйте снова");
			 return;
		 }
		 if ($('#mail-history > div').last().attr('class')=='mail-msg-person')
		 {
			 markup=mail_msg_me.replaceAll('##date##', date);
			 markup=markup.replaceAll('##message##', message);
			 markup=markup.replaceAll('##ava_me##', sender_ava);
			 $('#mail-history').append(markup); 
		 }
		 else
		 {
			 $('#mail-history div.mail-msg-me').last().find('div:nth-child(1)').find('div:nth-child(1)').append(mail_msg_separate);
			 markup=short_message.replaceAll('##date##', date);
			 markup=markup.replaceAll('##message##', message);
			 $('#mail-history div.mail-msg-me').last().find('div:nth-child(1)').find('div:nth-child(1)').append(markup);
		 }
	 }
	 var res = AJAX ("messages.php", "send_message", JSON.stringify(data), "POST", true, f);

}

function unserialize (data) {
  // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
  // *       returns 1: ['Kevin', 'van', 'Zonneveld']
  // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
  // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
  var that = this,
    utf8Overhead = function (chr) {
      // http://phpjs.org/functions/unserialize:571#comment_95906
      var code = chr.charCodeAt(0);
      if (code < 0x0080) {
        return 0;
      }
      if (code < 0x0800) {
        return 1;
      }
      return 2;
    },
    error = function (type, msg, filename, line) {
      throw new that.window[type](msg, filename, line);
    },
    read_until = function (data, offset, stopchr) {
      var i = 2, buf = [], chr = data.slice(offset, offset + 1);

      while (chr != stopchr) {
        if ((i + offset) > data.length) {
          error('Error', 'Invalid');
        }
        buf.push(chr);
        chr = data.slice(offset + (i - 1), offset + i);
        i += 1;
      }
      return [buf.length, buf.join('')];
    },
    read_chrs = function (data, offset, length) {
      var i, chr, buf;

      buf = [];
      for (i = 0; i < length; i++) {
        chr = data.slice(offset + (i - 1), offset + i);
        buf.push(chr);
        length -= utf8Overhead(chr);
      }
      return [buf.length, buf.join('')];
    },
    _unserialize = function (data, offset) {
      var dtype, dataoffset, keyandchrs, keys, contig,
        length, array, readdata, readData, ccount,
        stringlength, i, key, kprops, kchrs, vprops,
        vchrs, value, chrs = 0,
        typeconvert = function (x) {
          return x;
        };

      if (!offset) {
        offset = 0;
      }
      dtype = (data.slice(offset, offset + 1)).toLowerCase();

      dataoffset = offset + 2;

      switch (dtype) {
        case 'i':
          typeconvert = function (x) {
            return parseInt(x, 10);
          };
          readData = read_until(data, dataoffset, ';');
          chrs = readData[0];
          readdata = readData[1];
          dataoffset += chrs + 1;
          break;
        case 'b':
          typeconvert = function (x) {
            return parseInt(x, 10) !== 0;
          };
          readData = read_until(data, dataoffset, ';');
          chrs = readData[0];
          readdata = readData[1];
          dataoffset += chrs + 1;
          break;
        case 'd':
          typeconvert = function (x) {
            return parseFloat(x);
          };
          readData = read_until(data, dataoffset, ';');
          chrs = readData[0];
          readdata = readData[1];
          dataoffset += chrs + 1;
          break;
        case 'n':
          readdata = null;
          break;
        case 's':
          ccount = read_until(data, dataoffset, ':');
          chrs = ccount[0];
          stringlength = ccount[1];
          dataoffset += chrs + 2;

          readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10));
          chrs = readData[0];
          readdata = readData[1];
          dataoffset += chrs + 2;
          if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) {
            error('SyntaxError', 'String length mismatch');
          }
          break;
        case 'a':
          readdata = {};

          keyandchrs = read_until(data, dataoffset, ':');
          chrs = keyandchrs[0];
          keys = keyandchrs[1];
          dataoffset += chrs + 2;

          length = parseInt(keys, 10);
          contig = true;

          for (i = 0; i < length; i++) {
            kprops = _unserialize(data, dataoffset);
            kchrs = kprops[1];
            key = kprops[2];
            dataoffset += kchrs;

            vprops = _unserialize(data, dataoffset);
            vchrs = vprops[1];
            value = vprops[2];
            dataoffset += vchrs;

            if (key !== i)
              contig = false;

            readdata[key] = value;
          }

          if (contig) {
            array = new Array(length);
            for (i = 0; i < length; i++)
              array[i] = readdata[i];
            readdata = array;
          }

          dataoffset += 1;
          break;
        default:
          error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
          break;
      }
      return [dtype, dataoffset - offset, typeconvert(readdata)];
    }
  ;

  return _unserialize((data + ''), 0)[2];
}
/***************************************
*/

function find_adverts(p_start_page)
{
	 var data={};
	 data.start_page=p_start_page;
	 data.rubric_buy=$('input[name="buy"]').prop("checked");
	 data.rubric_sell=$('input[name="sell"]').prop("checked");
	 data.rubric_change=$('input[name="change"]').prop("checked");
	 data.categ_ekipa=$('input[name="ekipa"]').prop("checked");
	 data.categ_sportpit=$('input[name="sportpit"]').prop("checked");
	 data.categ_hardware=$('input[name="hardware"]').prop("checked");
	 data.categ_other=$('input[name="other"]').prop("checked");
	 data.ekypa_type_shirt=$('input[name="ekipa_press"]').prop("checked");
	 data.ekypa_type_kombez=$('input[name="ekipa_kombez"]').prop("checked");
	 data.ekypa_type_wraps=$('input[name="ekipa_wrap"]').prop("checked");
	 data.ekypa_type_belt=$('input[name="ekipa_poyas"]').prop("checked");
	 data.ekypa_type_boots=$('input[name="ekipa_boots"]').prop("checked");
	 
	 var f=function(response)
	 {
		 var markup, count;
		 $('#advert_block_search .ajax_search_result').remove();
		 markup=ajax_search_result_block.replaceAll('##block_type##', 'adverts_main');
		 markup=markup.replaceAll('##what_is_find##', 'объявлений');
		 markup=markup.replaceAll('##found##', 'Найдено');
		 
		 $('#ajax_loader_album_present').remove();
		 
		 markup=markup.replaceAll('##count_result##', response.adverts_count);
		 $('#advert_block_search .wrap_search_block').append(markup);
		 
		 if (response.status=="no adverts")
		 {
			 $('#adverts_main').prepend('<p><b>Попробуйте другие параметры для поиска...</b></p>');
		 }
		 else
		 {
			 var adverts=response.adverts;
			 $('#advert_block_search .search_paginator').html(response.paginator);
			 var rubrica = { 'sell':'Продам','buy':'Куплю','change':'Обменяю'};
			 var category = { 'ekipa':'Экипировка','sportpit':'Спортивное питание','equipment':'Оборудование','other':'Другое'};
			 var ekip_type = { 'none':'none','shirt':'Жимовая майка','kombez':'Комбез','wraps':'Бинты','boots':'Обувь','belt':'Пояс'};
			 
			 for(resp in adverts)
			 {
				  markup=markup_advert_in_search_block.replaceAll('##rubric_type##', rubrica[adverts[resp].rubric]);
				  markup=markup.replaceAll('##kateg_type##', category[adverts[resp].category]);
				  markup=markup.replaceAll('##date##', formatDate(adverts[resp].date));
				  markup=markup.replaceAll('##user_id##', adverts[resp].user_id);
				  markup=markup.replaceAll('##user_name##', adverts[resp].user_name);
				  markup=markup.replaceAll('##advert_id##', adverts[resp].id);
				  markup=markup.replaceAll('##phone_h##', adverts[resp].phone);
				  markup=markup.replaceAll('##email_h##', adverts[resp].email);
				  markup=markup.replaceAll('##scype_h##', adverts[resp].skype);
				  markup=markup.replaceAll('##advert_text##', adverts[resp].text);
				  
				 $('#adverts_main').append(markup);
			 }
		 }
		 
	 }	
	 
	 $('#advert_block_search').append(ajax_album_loader_present);
	 var res = AJAX ("find.php", "find_advert", JSON.stringify(data), "POST", true, f);	 
}

function find_lifter(p_start_page)
{
	 var data={};
	 data.start_page=p_start_page;
	 data.name=$('input[name="user_name"]').val();
	 data.age_from=$('select[name="day_of_birth"]').val();
	 data.age_to=$('select[name="day_of_birth"]').eq(1).val();
	 data.set_date_of_birth=$('input[name="set_date_of_birth"]').prop("checked");
	 data.set_date_of_birth_day=$('select[name="day_of_birth"]').eq(2).val();
	 data.set_date_of_birth_month=$('select[name="month_of_birth"]').val();
	 data.set_date_of_birth_year=$('select[name="year_of_birth"]').val();
	 data.country=$('select[name="contry"]').val();
	 data.region=$('select[name="region"]').val();
	 data.city=$('select[name="city"]').val();
	 data.set_power_data=$('input[name="set_power_data"]').prop("checked");
	 data.squat_from=$('select[name="day_of_birth"]').eq(3).val();
	 data.squat_to=$('select').eq(9).val();
	 data.press_from=$('select').eq(10).val();
	 data.press_to=$('select').eq(11).val();
	 data.dlift_from=$('select').eq(12).val();
	 data.dlift_to=$('select').eq(13).val();
	 data.total_from=$('select').eq(14).val();
	 data.total_to=$('select').eq(15).val();
	 data.set_antropometr_data=$('input[name="set_antropometr_data"]').prop("checked");
	 data.height_from=$('select').eq(16).val();
	 data.height_to=$('select').eq(17).val();
	 data.weight_from=$('select').eq(18).val();
	 data.weight_to=$('select').eq(19).val();
	 data.set_federation=$('input[name="set_federation"]').prop("checked");
	 data.ipf=$('input[name="ipf"]').prop("checked");
	 data.wpc=$('input[name="wpc"]').prop("checked");
	 data.wpo=$('input[name="wpo"]').prop("checked");
	 data.gpc=$('input[name="gpc"]').prop("checked");
	 data.wdfpf=$('input[name="wdfpf"]').prop("checked");
	 data.awpc=$('input[name="awpc"]').prop("checked");
	 data.ipa=$('input[name="ipa"]').prop("checked");
	 data.gpu=$('input[name="gpu"]').prop("checked");
	 data.udfpf=$('input[name="udfpf"]').prop("checked");
	 data.raw=$('input[name="raw"]').prop("checked");
	 data.set_tityl=$('input[name="set_tityl"]').prop("checked");
	 data.rate_3jun=$('input[name="rate_3jun"]').prop("checked");
	 data.rate_2jun=$('input[name="rate_2jun"]').prop("checked");
	 data.rate_1jun=$('input[name="rate_1jun"]').prop("checked");
	 data.rate_3man=$('input[name="rate_3man"]').prop("checked");
	 data.rate_2man=$('input[name="rate_2man"]').prop("checked");
	 data.rate_1man=$('input[name="rate_1man"]').prop("checked");
	 data.rate_kms=$('input[name="rate_kms"]').prop("checked");
	 data.rate_ms=$('input[name="rate_ms"]').prop("checked");
	 data.rate_msmk=$('input[name="rate_msmk"]').prop("checked");
	 data.rate_zms=$('input[name="rate_zms"]').prop("checked");
	 
	 var f=function(response)
	 {
		 var markup, count;
		 $('#lifter_block_search .ajax_search_result').remove();
		 markup=ajax_search_result_block.replaceAll('##block_type##', 'lifters_main');
		 markup=markup.replaceAll('##what_is_find##', 'спортсменов');
		 markup=markup.replaceAll('##found##', 'Найдено');
		 
		 $('#ajax_loader_album_present').remove();
		 
		 markup=markup.replaceAll('##count_result##', response.lifters_count);
		 $('#lifter_block_search .wrap_search_block').append(markup);
		 
		 if (response.status=="no users")
		 {
			 $('#lifters_main').prepend('<p><b>Попробуйте другие параметры для поиска...</b></p>');
		 }
		 else
		 {
			 var lifters=response.lifters;
			 $('#lifter_block_search .search_paginator').html(response.paginator);
			 
			 for(resp in lifters)
			 {
				 markup=markup_lifter_block.replaceAll('##user_id##', lifters[resp].id);
				 
				 if (lifters[resp].avatar150!=null)
				 {
					 markup=markup.replaceAll('##user_ava_150##', 'user_photos/mini/'+lifters[resp].avatar150);
				 }
				 else
				 {
					 markup=markup.replaceAll('##user_ava_150##', 'images/no_avatar150.png');
				 }
				 
				 if (lifters[resp].last_time==null||((time()-lifters[resp].last_time)>300))
				 {
					 markup=markup.replaceAll('##online_status##', 'offline');
					 markup=markup.replaceAll('##status_text##', 'Offline');
				 }
				 else
				 {
					  markup=markup.replaceAll('##online_status##', 'online_now');
					  markup=markup.replaceAll('##status_text##', 'Online');
				 }
				 
				 markup=markup.replaceAll('##user_first_last_name##', lifters[resp].first_name+' '+lifters[resp].last_name);
				 if (lifters[resp].country_name_ru==null)
				 {
					 lifters[resp].country_name_ru='';
				 }
				 markup=markup.replaceAll('##country##', lifters[resp].country_name_ru);
				 if (lifters[resp].city_name_ru==null)
				 {
					 lifters[resp].city_name_ru='';
					 markup=markup.replaceAll('##city##', lifters[resp].city_name_ru);
				 }
				 else
				 {
					 markup=markup.replaceAll('##city##', ', '+lifters[resp].city_name_ru);
				 }
				 
				 if (lifters[resp].date_of_birth==null)
				 {
					 lifters[resp].date_of_birth='';					 
				 }
				 else
				 {
					 lifters[resp].date_of_birth=plural(birthDateToAge(lifters[resp].date_of_birth));
				 }
				 markup=markup.replaceAll('##age##', lifters[resp].date_of_birth);				 
				 
				  if (lifters[resp].squat==null)
				 {
					 lifters[resp].squat='';
					 markup=markup.replaceAll('##squat##', lifters[resp].squat);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##squat##', lifters[resp].squat+' кг');
				 }
				 if (lifters[resp].benchpress==null)
				 {
					 lifters[resp].benchpress='';
					 markup=markup.replaceAll('##b_press##', lifters[resp].benchpress);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##b_press##', lifters[resp].benchpress+' кг');
				 }
				 if (lifters[resp].deadlift==null)
				 {
					 lifters[resp].deadlift='';
					 markup=markup.replaceAll('##d_lift##', lifters[resp].deadlift);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##d_lift##', lifters[resp].deadlift+' кг');
				 }
				 if (lifters[resp].total==null)
				 {
					 lifters[resp].total='';
					 markup=markup.replaceAll('##total##', lifters[resp].total);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##total##', lifters[resp].total+' кг');
				 }
				
				 var rang = { '3jun':'3й юн.','2jun':'2й юн.','1jun':'1й юн.','3man':'3й взр.','2man':'2й взр.','1man':'1й взр.','kms':'КМС','ms':'МС','msmc':'МСМК','zms':'ЗМС' };
				  if (lifters[resp].level==null)
				 {
					 lifters[resp].level='';	
					 markup=markup.replaceAll('##rang##', lifters[resp].level);
				 }
				 else
				 {
					 markup=markup.replaceAll('##rang##', rang[lifters[resp].level]);
				 }
				 
				 if (lifters[resp].federation==null)
				 {
					 lifters[resp].federation='';
					 markup=markup.replaceAll('##federation##', lifters[resp].federation);
				 }
				 else
				{
					 var federation = unserialize(lifters[resp].federation);
					 var federation_list=0;
					 for(p in federation) 
					 {
						 if (federation[p])
						 {
							 if (federation_list!=0)
							 {
								 federation_list=federation_list+', '+p;
							 }
							 else
							 {
								 federation_list=p;
							 }
						 }
					 }
					 if (federation_list.length>13)
					 {
						 federation_list='<span title="'+federation_list+'">'+federation_list.substr(0,13)+'..</span';
					 }
					 markup=markup.replaceAll('##federation##', federation_list.toUpperCase());
				} 
				 if (lifters[resp].friend==null)
				 {
					 markup=markup.replaceAll('##friend_btn_name##', "Дружить");
					 markup=markup.replaceAll('##function##', "add_to_friends(this,"+lifters[resp].id+")");
				 }
				 else
				 {
					 markup=markup.replaceAll('##friend_btn_name##', "Отказаться от дружбы");
					 markup=markup.replaceAll('##function##', "delete_from_friends(this,"+lifters[resp].id+")");
				 }
				 
				 $('#lifters_main').prepend(markup);
				 if (response.my_id==lifters[resp].id)
				 {
					 $('.lifter_block input[name="friend_btn"]').first().remove();
				 }
			 }
		 }
	 }
	 
	 $('#lifter_block_search').append(ajax_album_loader_present);
	 var res = AJAX ("find.php", "find_lifter", JSON.stringify(data), "POST", true, f);
	 
}
function get_my_friends(p_start_page)
{
	 $('ul.acount li a').removeClass('active_item');
	 $('ul.acount li a').eq(5).addClass('active_item');
	 
	 header_block=markup_header.replace('##title##','Мои друзья');
     $('#content').html(header_block);
	 $('#content').append(markup_wrap_search_block);
	 
	 var data={};
	 data.start_page=p_start_page;
	 
	 var f=function(response)
	 {
		 var markup, count;
		 
		 markup=ajax_search_result_block.replaceAll('##block_type##', 'lifters_main');
		 markup=markup.replaceAll('##what_is_find##', 'друзей');
		 markup=markup.replaceAll('##found##', 'Вы добавили');
		 
		 $('#ajax_loader_album').remove();
		 
		 markup=markup.replaceAll('##count_result##', response.lifters_count);
		 $('.wrap_search_block').append(markup);
		 
		 if (response.status=="no users")
		 {
			 $('#lifters_main').prepend('<p><b>У вас нет ни одного добавленного друга...</b></p>');
		 }
		 else
		 {
			 var lifters=response.lifters;
			 $('#lifter_block_search .search_paginator').html(response.paginator);
			 
			 for(resp in lifters)
			 {
				 markup=markup_lifter_block.replaceAll('##user_id##', lifters[resp].id);
				 
				 if (lifters[resp].avatar150!=null)
				 {
					 markup=markup.replaceAll('##user_ava_150##', 'user_photos/mini/'+lifters[resp].avatar150);
				 }
				 else
				 {
					 markup=markup.replaceAll('##user_ava_150##', 'images/no_avatar150.png');
				 }
				 
				 if (lifters[resp].last_time==null||((time()-lifters[resp].last_time)>300))
				 {
					 markup=markup.replaceAll('##online_status##', 'offline');
					 markup=markup.replaceAll('##status_text##', 'Offline');
				 }
				 else
				 {
					  markup=markup.replaceAll('##online_status##', 'online_now');
					  markup=markup.replaceAll('##status_text##', 'Online');
				 }
				 
				 markup=markup.replaceAll('##user_first_last_name##', lifters[resp].first_name+' '+lifters[resp].last_name);
				 if (lifters[resp].country_name_ru==null)
				 {
					 lifters[resp].country_name_ru='';
				 }
				 markup=markup.replaceAll('##country##', lifters[resp].country_name_ru);
				 if (lifters[resp].city_name_ru==null)
				 {
					 lifters[resp].city_name_ru='';
					 markup=markup.replaceAll('##city##', lifters[resp].city_name_ru);
				 }
				 else
				 {
					 markup=markup.replaceAll('##city##', ', '+lifters[resp].city_name_ru);
				 }
				 
				 if (lifters[resp].date_of_birth==null)
				 {
					 lifters[resp].date_of_birth='';					 
				 }
				 else
				 {
					 lifters[resp].date_of_birth=plural(birthDateToAge(lifters[resp].date_of_birth));
				 }
				 markup=markup.replaceAll('##age##', lifters[resp].date_of_birth);				 
				 
				  if (lifters[resp].squat==null)
				 {
					 lifters[resp].squat='';
					 markup=markup.replaceAll('##squat##', lifters[resp].squat);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##squat##', lifters[resp].squat+' кг');
				 }
				 if (lifters[resp].benchpress==null)
				 {
					 lifters[resp].benchpress='';
					 markup=markup.replaceAll('##b_press##', lifters[resp].benchpress);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##b_press##', lifters[resp].benchpress+' кг');
				 }
				 if (lifters[resp].deadlift==null)
				 {
					 lifters[resp].deadlift='';
					 markup=markup.replaceAll('##d_lift##', lifters[resp].deadlift);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##d_lift##', lifters[resp].deadlift+' кг');
				 }
				 if (lifters[resp].total==null)
				 {
					 lifters[resp].total='';
					 markup=markup.replaceAll('##total##', lifters[resp].total);	
				 }
				 else
				 {
					 markup=markup.replaceAll('##total##', lifters[resp].total+' кг');
				 }
				
				 var rang = { '3jun':'3й юн.','2jun':'2й юн.','1jun':'1й юн.','3man':'3й взр.','2man':'2й взр.','1man':'1й взр.','kms':'КМС','ms':'МС','msmc':'МСМК','zms':'ЗМС' };
				  if (lifters[resp].level==null)
				 {
					 lifters[resp].level='';	
					 markup=markup.replaceAll('##rang##', lifters[resp].level);
				 }
				 else
				 {
					 markup=markup.replaceAll('##rang##', rang[lifters[resp].level]);
				 }
				 
				 if (lifters[resp].federation==null)
				 {
					 lifters[resp].federation='';
					 markup=markup.replaceAll('##federation##', lifters[resp].federation);
				 }
				 else
				{
					 var federation = unserialize(lifters[resp].federation);
					 var federation_list=0;
					 for(p in federation) 
					 {
						 if (federation[p])
						 {
							 if (federation_list!=0)
							 {
								 federation_list=federation_list+', '+p;
							 }
							 else
							 {
								 federation_list=p;
							 }
						 }
					 }
					 if (federation_list.length>13)
					 {
						 federation_list='<span title="'+federation_list+'">'+federation_list.substr(0,13)+'..</span';
					 }
					 markup=markup.replaceAll('##federation##', federation_list.toUpperCase());
				} 
				 
				 markup=markup.replaceAll('##friend_btn_name##', "Отказаться от дружбы");
				 markup=markup.replaceAll('##function##', "remove_from_friends(this,"+lifters[resp].id+")");				 
				 
				 $('#lifters_main').prepend(markup);
				 if (response.my_id==lifters[resp].id)
				 {
					 $('.lifter_block input[name="friend_btn"]').first().remove();
				 }
			 }
		 }
		 $(".ajax_search_result").css('border-top','0');
		 $(".wrap_search_block").css('padding-top','0');		 
	 }
	 
	 $('.breadcrumb').after(ajax_album_loader);
	 var res = AJAX ("find.php", "find_lifter_friends", JSON.stringify(data), "POST", true, f);
}
function get_my_adverts(p_start_page)
{
	 $('ul.acount li a').removeClass('active_item');
	 $('ul.acount li a').eq(4).addClass('active_item');
	 
	 header_block=markup_header.replace('##title##','Мои объявления');
     $('#content').html(header_block);
	 $('#content').append(markup_wrap_search_block);
	 
	 var data={};
	 data.start_page=p_start_page;
	 
	 var f=function(response)
     {
		 var markup, count;
		 $('#lifter_block_search .ajax_search_result').remove();
		 markup=ajax_search_result_block.replaceAll('ajax_search_result', 'ajax_my_adverts');
		 markup= markup.replaceAll('##block_type##', 'adverts_main');
		 markup=markup.replaceAll('##what_is_find##', 'объявлений');
		 markup=markup.replaceAll('##found##', 'Вы опубликовали');
		 
		 $('#ajax_loader_album').remove();
		 
		 markup=markup.replaceAll('##count_result##', response.adverts_count);
		 $('.wrap_search_block').append(markup);
		 
		 if (response.status=="no adverts")
		 {
			 $('.wrap_search_block').html(markup_no_my_adverts);
		 }
		 else
		 {
			 var adverts=response.adverts;
			 $('.search_paginator').html(response.paginator);
			 var rubrica = { 'sell':'Продам','buy':'Куплю','change':'Обменяю'};
			 var category = { 'ekipa':'Экипировка','sportpit':'Спортивное питание','equipment':'Оборудование','other':'Другое'};
			 var ekip_type = { 'none':'none','shirt':'Жимовая майка','kombez':'Комбез','wraps':'Бинты','boots':'Обувь','belt':'Пояс'};
			 
			 for(resp in adverts)
			 {
				  markup=markup_my_advert_block.replaceAll('##rubric##', rubrica[adverts[resp].rubric]);
				  markup=markup.replaceAll('##categ##', category[adverts[resp].category]);
				  markup=markup.replaceAll('##date##', formatDate(adverts[resp].date));
				  markup=markup.replaceAll('##text##', adverts[resp].text);
				  markup=markup.replaceAll('##advert_id##', adverts[resp].id);
				  markup=markup.replaceAll('##phone_h##', adverts[resp].phone);
				  markup=markup.replaceAll('##email_h##', adverts[resp].email);
				  markup=markup.replaceAll('##scype_h##', adverts[resp].skype);				  
				  
				  $('#adverts_main').append(markup);
			 }
			 $('.wrap_search_block').append(markup_button_new_advert);
		 }
	 }
	 $('.breadcrumb').after(ajax_album_loader);
	 var res = AJAX ("find.php", "get_my_adverts", JSON.stringify(data), "POST", true, f);
}

function add_to_friends(p_elem, p_friend_id)
{
	 var data={};
	 data.friend_id=p_friend_id;
	 
	 var f=function(response)
     {
		 if (response.status=="added")
		 {
			 $(p_elem).val("Отказаться от дружбы");
			 $(p_elem).attr('onclick','delete_from_friends(this,'+ p_friend_id+')')
		 }
		 else
		 {
			 alert("Возникла ошибка, пользователь не был добавлен в друзья");
		 }
	 }
	 var res = AJAX ("personal_data.php", "add_to_friends", JSON.stringify(data), "POST", true, f);
}

function delete_from_friends(p_elem, p_friend_id)
{
	 var data={};
	 data.friend_id=p_friend_id;
	 
	 var f=function(response)
     {
		 if (response.status=="deleted")
		 {
			 $(p_elem).val("Дружить");
			 $(p_elem).attr('onclick','add_to_friends(this,'+ p_friend_id+')')
		 }
		 else
		 {
			 alert("Возникла ошибка, пользователь не был удален из друзей");
		 }
	 }
	 var res = AJAX ("personal_data.php", "delete_from_friends", JSON.stringify(data), "POST", true, f);
}

function remove_from_friends(p_elem, p_friend_id)
{
	 var data={};
	 data.friend_id=p_friend_id;
	 
	 var f=function(response)
     {
		 if (response.status=="deleted")
		 {
			 $(p_elem).parent().parent().parent().remove();	
			 $('.ajax_search_result h2 b').html($('.ajax_search_result h2 b').html()-1);
		 }
		 else
		 {
			 alert("Возникла ошибка, пользователь не был удалён из друзей");
		 }
	 }
	 var res = AJAX ("personal_data.php", "delete_from_friends", JSON.stringify(data), "POST", true, f);
}



function quick_message(p_receiver_id)
{
	 if (!$.trim($('#popup_message textarea').val()))
	 {
		 alert("Вы не ввели текст сообщения!");
		 return;
	 }
	 
	 var data={};
	 data.receiver_id=p_receiver_id;
	 data.message=$('#popup_message textarea').val();
	 
	 var f=function(response)
     {
		 if (response.status!='message sent')
		 {
			 alert("Сообщение не было отправлено, возникли технические проблемы. Попробуйте снова");
			 return;
		 }
		 else
		 {
			 $('#hide-layout').fadeOut(300);
			 $('#popup_message').fadeOut(300);
		 }
	 }
	 var res = AJAX ("messages.php", "send_message", JSON.stringify(data), "POST", true, f);	 
}

function checkNewsCheckboxes(data)
{
	 if (localStorage['photo_news']!=undefined)
	 {
		 data.photo_checked=(localStorage['photo_news']=="true");		  
		 
		  if (localStorage['photo_news']=="true")
		 {
			 $('input[name="photo_news"]').parent().attr('class', "checked");
			 $('input[name="photo_news"]').attr('checked', true);
		 }
		 else
		 {
			 $('input[name="photo_news"]').parent().attr('class', "");
			 $('input[name="photo_news"]').attr('checked', false);
		 }		 
	 }
	 else
	 {
		 data.photo_checked=$('input[name="photo_news"]').prop("checked");
		 localStorage['photo_news']=data.photo_checked;
	 }
	 
	 if (localStorage['video_news']!=undefined)
	 {
		 data.video_checked=(localStorage['video_news']=="true");
		 
		 if (localStorage['video_news']=="true")
		 {
			 $('input[name="video_news"]').parent().attr('class', "checked");
			 $('input[name="video_news"]').attr('checked', true);
		 }
		 else
		 {
			 $('input[name="video_news"]').parent().attr('class', "");
			 $('input[name="video_news"]').attr('checked', false);
		 }		 
	 }
	 else
	 {
		 data.video_checked=$('input[name="video_news"]').prop("checked");
		 localStorage['video_news']=data.video_checked;
	 }
	 
	 if (localStorage['advert_news']!=undefined)
	 {
		 data.advert_checked=(localStorage['advert_news']=="true");		 
		 
		 if (localStorage['advert_news']=="true")
		 {
			 $('input[name="advert_news"]').parent().attr('class', "checked");
			 $('input[name="advert_news"]').attr('checked', true);
		 }
		 else
		 {
			 $('input[name="advert_news"]').parent().attr('class', "");
			 $('input[name="advert_news"]').attr('checked', false);
		 }		 
	 }
	 else
	 {
		 data.advert_checked=$('input[name="advert_news"]').prop("checked");
		 localStorage['advert_news']=data.advert_checked;
	 }	
	 return data;
}

function news(p_start_page)
{
	 $('ul.acount li a').removeClass('active_item');
	 $('ul.acount li a').eq(5).addClass('active_item');
	 
	 header_block=markup_header.replace('##title##','Новости');
     $('#content').html(header_block);
	 $('#content').append(markup_news_filters);
	 $("input:checkbox").uniform();	 
	 
	 var data={};
	 data.start_page=p_start_page;
	 
	 data=checkNewsCheckboxes(data);
	 
	 var f=function(response)
	 {
		 $('#ajax_loader_album').remove();
		 var markup=markup_news_main.replaceAll('##count_result##', response.news_count);
		 $('#content').append(markup);
		 
		 if (response.status=='no news')
		 {
			 $('.news').html(markup_no_news).css('padding-bottom','26px');
			 return;
		 }
		 else
		 {
			 var news=response.news;
			 $('.search_paginator').html(response.paginator);
			 
			 var user_id_prev, link, title, date, format_date, date_prev, feeds_id, like_count, dislike_count, comments_count, rubric, category, phone, email, skype, text, album_name, album_id, user_name, user_id, news_type, news_type_prev, var_like, var_dislike, rel_photo;	

			 var rubrica = { 'sell':'Продам','buy':'Куплю','change':'Обменяю'};
			 var categ = { 'ekipa':'Экипировка','sportpit':'Спортивное питание','equipment':'Оборудование','other':'Другое'};
			 rel_photo=0;
			for(resp in news)
			{				 
				 link=news[resp].link;
				 title=news[resp].title;
				 format_date=formatDateTime(news[resp].date);
				 date=news[resp].date;
				 like_count=news[resp].like_count;
				 dislike_count=news[resp].dislike_count;
				 comments_count=news[resp].comments_count;
				 album_name=news[resp].album_name;
				 album_id=news[resp].album_id;
				 user_name=news[resp].user_name;
				 user_id=news[resp].user_id;
				 rubric=rubrica[news[resp].rubric];
				 category=categ[news[resp].category];
				 phone=news[resp].phone;
				 email=news[resp].email;
				 skype=news[resp].skype;
				 text=news[resp].text;
				 feeds_id=news[resp].feeds_id;					
				 
				 switch (news[resp].news_type)
				 {				 
					 case 'video':						 
						 if (user_id_prev && user_id_prev==user_id &&(date_prev && ((date-date_prev)<300))&&news[resp].news_type==news_type_prev)
						 {
							 markup=markup_video_one.replaceAll('##link##', link);
							 markup=markup.replaceAll('##title##', title);
							 $('.video_news_wrap').last().append(markup);
							 var_like=parseInt($('.video_news_wrap').last().parent().parent().find('b.like_count').text());
							 var_like=var_like+parseInt(like_count);
							 $('.video_news_wrap').last().parent().parent().find('b.like_count').text(var_like);
							 var_dislike=parseInt($('.video_news_wrap').last().parent().parent().find('b.unlike_count').text());
							 var_dislike=var_dislike+parseInt(dislike_count);
							 $('.video_news_wrap').last().parent().parent().find('b.unlike_count').text(var_dislike);
						 }
						 else
						 {
							 markup=markup_news_video.replaceAll('##like_count##', like_count);
							 markup=markup.replaceAll('##unlike_count##', dislike_count);
							 markup=markup.replaceAll('##comments_count##', comments_count);
							 markup=markup.replaceAll('##user_id##', user_id);
							 markup=markup.replaceAll('##user_name##', user_name);
							 markup=markup.replaceAll('##videoalbum_id##', album_id);
							 markup=markup.replaceAll('##album_name##', album_name);
							 markup=markup.replaceAll('##date##', format_date);
							 markup=markup.replaceAll('##link##', link);
							 markup=markup.replaceAll('##title##', title);
							 $('.news > ul').append(markup);
						 }
						 date_prev=date;
						 user_id_prev=user_id;
						 news_type_prev=news[resp].news_type;
						 break;
					 case 'photo':
						  if (user_id_prev!=null && user_id_prev==user_id &&(date_prev!=null && ((date-date_prev)<300))&&news[resp].news_type==news_type_prev)
						 {
							 markup=markup_photo_one.replaceAll('##link##', link);
							 markup=markup.replaceAll('##title##', title);
							 markup=markup.replaceAll('##rel_photo##', rel_photo);
							 $('.photo_preview_news').last().append(markup);
							 var_like=parseInt($('.photo_preview_news').last().parent().parent().find('b.like_count').text());
							 var_like=var_like+parseInt(like_count);
							 $('.photo_preview_news').last().parent().parent().find('b.like_count').text(var_like);
							 var_dislike=parseInt($('.photo_preview_news').last().parent().parent().find('b.unlike_count').text());
							 var_dislike=var_dislike+parseInt(dislike_count);
							 $('.photo_preview_news').last().parent().parent().find('b.unlike_count').text(var_dislike);
						 }
						 else
						 {
							 markup=markup_news_photo.replaceAll('##like_count##', like_count);
							 markup=markup.replaceAll('##dislike_count##', dislike_count);
							 markup=markup.replaceAll('##comments_count##', comments_count);
							 markup=markup.replaceAll('##user_id##', user_id);
							 markup=markup.replaceAll('##user_name##', user_name);
							 markup=markup.replaceAll('##photoalbum_id##', album_id);
							 markup=markup.replaceAll('##album_name##', album_name);
							 markup=markup.replaceAll('##date##', format_date);
							 markup=markup.replaceAll('##link##', link);
							 markup=markup.replaceAll('##title##', title);
							 rel_photo++;
							 markup=markup.replaceAll('##rel_photo##', rel_photo);
							 $('.news > ul').append(markup);
						 }
						 date_prev=date;
						 user_id_prev=user_id;
						 news_type_prev=news[resp].news_type;
						 break;	
					 case 'advert':
						 markup=markup_news_advert.replaceAll('##user_id##', user_id);
						 markup=markup.replaceAll('##user_name##', user_name);
						 markup=markup.replaceAll('##date##', format_date);
						 markup=markup.replaceAll('##link##', link);
						 markup=markup.replaceAll('##text##', text);	
						 markup=markup.replaceAll('##rubric##', rubric);
						 markup=markup.replaceAll('##category##', category);
						 markup=markup.replaceAll('##phone_h##', phone);
						 markup=markup.replaceAll('##email_h##', email);
						 markup=markup.replaceAll('##skype_h##', skype);
						 markup=markup.replaceAll('##feeds_id##', feeds_id);
						 $('.news > ul').append(markup);
						 $('.news > ul >li').last().attr('style','padding-bottom:0');
						 date_prev=date;
						 user_id_prev=user_id;
						 news_type_prev=news[resp].news_type;
						 break;	 
				 }
			}	
			$("a[class^='gallery']").prettyPhoto();
		 }
	 }
	 $('.content-filter').after(ajax_album_loader);	
	 var res = AJAX ("find.php", "get_news", JSON.stringify(data), "POST", true, f);	
}

function get_video_comments_and_likes(p_videos_link_name)
{
	 var data={}, markup, comments;
	 data.videos_link_name=p_videos_link_name;
	 
	 var f=function(response)
	 {
		 markup=markup_photo_actions_content_iframe_video_popup.replaceAll('##date##', formatDateTime(response.likes[0].date_of_added));
		 markup=markup.replaceAll('##like_count##', response.likes[0].like_count);
		 markup=markup.replaceAll('##dislike_count##', response.likes[0].dislike_count);
		 $('.photo_actions').html(markup);
		 
		 comments=response.comments;
		 $('.photo_comments').html("");
		 
		 for(resp in comments)
		 {
			 markup=markup_iframe_video_popup_comment.replaceAll('##user_name##', comments[resp].user_name);	
			 markup=markup.replaceAll('##date##', formatDateTime(comments[resp].date));
			 markup=markup.replaceAll('##text##', comments[resp].text);
			 
			 $('.photo_comments').append(markup);
		 }
	 }
	 var res = AJAX ("get_comments.php", "get_video_comments_and_likes", JSON.stringify(data), "POST", true, f);
}

function send_video_comment(p_videos_link_name, p_text, p_comments_block)
{
	 var data={}, markup;
	 data.videos_link_name=p_videos_link_name;
	 data.text=p_text; 
		 
	 $('.photo_comments').append(markup);
	 
	 var f=function(response)
	 {
			 markup=markup_iframe_video_popup_comment.replaceAll('##user_name##', response.user_name);	
			 markup=markup.replaceAll('##date##', formatDateTime(response.date));
			 markup=markup.replaceAll('##text##', response.text);
			 
			 $(p_comments_block).append(markup);
	 }	 
	 var res = AJAX ("get_comments.php", "insert_video_comment", JSON.stringify(data), "POST", true, f);
}

function send_photo_comment(p_photos_link_name, p_text, p_comments_block)
{
	 var data={}, markup;
	 data.photos_link_name=p_photos_link_name;
	 data.text=p_text; 
		 
	 $('.photo_comments').append(markup);
	 
	 var f=function(response)
	 {
			 markup=markup_iframe_video_popup_comment.replaceAll('##user_name##', response.user_name);	
			 markup=markup.replaceAll('##date##', formatDateTime(response.date));
			 markup=markup.replaceAll('##text##', response.text);
			 
			 $(p_comments_block).append(markup);
			 $('.pp_content').height(($('.pp_pic_holder').height()-40));
	 }	 
	 var res = AJAX ("get_comments.php", "insert_photo_comment", JSON.stringify(data), "POST", true, f);
}

function add_video_like(p_videos_link_name, p_like_status, p_like_block)
{
	 var data={};
	 data.videos_link_name=p_videos_link_name;
	 data.like_status=p_like_status;
	  
	 var f=function(response)
	 {
		 $(p_like_block).find('b').eq(0).html(response.likes[0].like_count);
		 $(p_like_block).find('b').eq(1).html(response.likes[0].dislike_count);		 
	 }	 
	 var res = AJAX ("get_comments.php", "add_video_like", JSON.stringify(data), "POST", true, f);	  
}

function add_photo_like(p_photos_link_name, p_like_status, p_like_block)
{
	 var data={};
	 data.photos_link_name=p_photos_link_name;
	 data.like_status=p_like_status;
	  
	 var f=function(response)
	 {
		 $(p_like_block).find('b').eq(0).html(response.likes[0].like_count);
		 $(p_like_block).find('b').eq(1).html(response.likes[0].dislike_count);		 
	 }	 
	 var res = AJAX ("get_comments.php", "add_photo_like", JSON.stringify(data), "POST", true, f);	  
}

Share = {
    vkontakte: function(purl, ptitle, pimg, text) {
        url  = 'http://vkontakte.ru/share.php?';
        url += 'url='          + encodeURIComponent(purl);
        url += '&title='       + encodeURIComponent(ptitle);
        url += '&description=' + encodeURIComponent(text);
        url += '&image='       + encodeURIComponent(pimg);
        url += '&noparse=true';
        Share.popup(url);
    },
    odnoklassniki: function(purl, text) {
        url  = 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1';
        url += '&st.comments=' + encodeURIComponent(text);
        url += '&st._surl='    + encodeURIComponent(purl);
        Share.popup(url);
    },
    facebook: function(purl, ptitle, pimg, text) {
        url  = 'https://www.facebook.com/dialog/feed?app_id=134530986736267';
        url += '&name='     + encodeURIComponent(ptitle);
        url += '&description='   + encodeURIComponent(text);
        url += '&link='       + encodeURIComponent(purl);
        url += '&picture=' + encodeURIComponent(pimg);
		url +='&redirect_uri=http://facebook.com/'
		/*
		url  = 'http://www.facebook.com/sharer.php?s=100';
        url += '&p[title]='     + encodeURIComponent(ptitle);
        url += '&p[summary]='   + encodeURIComponent(text);
        url += '&p[url]='       + encodeURIComponent(purl);
        url += '&p[images][0]=' + encodeURIComponent(pimg);
        Share.popup(url);
		*/
        Share.popup(url);
    },
    twitter: function(purl, ptitle) {
        url  = 'http://twitter.com/share?';
        url += 'text='      + encodeURIComponent(ptitle);
        url += '&url='      + encodeURIComponent(purl);
        url += '&counturl=' + encodeURIComponent(purl);
        Share.popup(url);
    },
    mailru: function(purl, ptitle, pimg, text) {
        url  = 'http://connect.mail.ru/share?';
        url += 'url='          + encodeURIComponent(purl);
        url += '&title='       + encodeURIComponent(ptitle);
        url += '&description=' + encodeURIComponent(text);
        url += '&imageurl='    + encodeURIComponent(pimg);
        Share.popup(url)
    },
	google_plus: function(purl) {
        url  = 'https://plus.google.com/share?';        
        url += 'url='      + encodeURIComponent(purl);        
        Share.popup(url);
    },

    popup: function(url) {
        window.open(url,'','toolbar=0,status=0,width=626,height=436');
    }
};

function share(p_social_type, p_elem, p_title)
{
	 var news_block=$(p_elem).parent().parent().parent().parent();
	 var icon=$(news_block).find('.news_info span');
	 var data={}, index, preview, description, advert_id, shared_id;
	 var links={};
     
	 if ($(icon).attr('class')=='photo_icon' || $(icon).attr('class')=='video_icon')
	 {
		if ($(icon).attr('class')=='photo_icon')
		{
			 preview=$(news_block).find('.photo_preview_news img').eq(0).attr("src");
			 description='На сайте www.powerliftingunites.com были добавлены интересные фото!!!';
			 $(news_block).find('.photo_preview_news img').each
			 (
				function()
				{				
					 index=$(this).attr("src").lastIndexOf('/');
					 links[$(this).attr("src").substr(index+1)]=$(this).attr("src").substr(index+1);
				}				
			);
			data.news_type='photo';
						
		}
		if ($(icon).attr('class')=='video_icon')
		{
			 preview=$(news_block).find('.video_news img').eq(0).attr("src");
			 description='На сайте www.powerliftingunites.com были добавлены интересные видео!!!';
			 $(news_block).find('.video_news img').each
			 (
				function()
				{				
					 links[$(this).attr("video")]=$(this).attr("video");
				}
			);
			data.news_type='video';			
		}
		
		var f=function(response)
		{
			shared_id=response.id;	 
		}			
		data.links=links;
		var res = AJAX ("soc_net.php", "get_soc_net", JSON.stringify(data), "POST", false, f);
		 switch (p_social_type)
		 {
			 case 'fb':			 
				 Share.facebook('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+shared_id, p_title, preview, description);		 
			 break;
			 case 'vk':
				 Share.vkontakte('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+shared_id, p_title, preview, description);
			 break;
			 case 'tw':
				 Share.twitter('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+shared_id, p_title);
			 break;
			 case 'ok':
				 Share.odnoklassniki('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+shared_id, p_title);
			 break;
			 case 'gp':
				 Share.google_plus('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+shared_id);
			 break;
			 case 'mail':
				 Share.mailru('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+shared_id, p_title, preview, description);
			 break;
		 }
	}
	else
	{
		 data.news_type='adverts';
		 preview='http://v-comp.com.ua/images/news/20140219185157616.jpg';
		 description='На сайте www.powerliftingunites.com было добавлено объявление!!!';
		 advert_id=$(news_block).find('.advert_news input[name="id"]').val();
		 switch (p_social_type)
		 {
			 case 'fb':			 
				 Share.facebook('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+advert_id, p_title, preview, description);		 
			 break;
			 case 'vk':
				 Share.vkontakte('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+advert_id, p_title, preview, description);
			 break;
			 case 'tw':
				 Share.twitter('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+advert_id, p_title);
			 break;
			 case 'ok':
				 Share.odnoklassniki('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+advert_id, p_title);
			 break;
			 case 'gp':
				 Share.google_plus('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+advert_id);
			 break;
			 case 'mail':
				 Share.mailru('http://www.powerliftingunites.com/external_'+data.news_type+'_view.php?id='+advert_id, p_title, preview, description);
			 break;
		 }	 
	}
}

function recovery_pass()
{
	 var data={};
	 data.email=$('#recovery input[name="email"]').val();
	 
	var f=function(response)
	{
		 if (response.is_email_register=="no")
		{
			 $('#recovery #error').text('Пользователь с таким email не зарегистрирован!');
			 $('#recovery #error').css('color','#FF0000');
		}
		 if (response.is_sent_email=="yes")
		{
			 $('#recovery #error').text('На Ваш email была отправлена ссылка для восстановления пароля!');
			 $('#recovery #error').css('color','#69A933');
		}
	}			
	
	var res = AJAX ("recovery.php", "recovery_pass", JSON.stringify(data), "POST", false, f);
}


